package com.jdbc.service;

import com.jdbc.dao.AccountDao;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;//调用持久层，用于完成数据库操作
    /**
     * 转账
     * @param sourceId--原账户id
     * @param targetId--目标账户id
     * @param money--转账金额
     * @return true:转账成功，false:转账失败
     */
    @Override
    public boolean transfer(int sourceId, int targetId, double money) {
        //1.获取原，目标账户余额
        double sourceBanlance=accountDao.findById(sourceId).getBalance();
        double targetBanlance=accountDao.findById(targetId).getBalance();

        //2.如果原账户余额不够，则转账失败；否则修改原，目标账户余额，转账成功
        if (sourceBanlance<money){
            return false;
        }else {
         int n1= accountDao.updateBalanceById(sourceId,sourceBanlance-money);
         int n2=accountDao.updateBalanceById(targetId,targetBanlance+money);
            if (n1==0||n2==0){
                return false;
            }else {
                return true;
            }
        }
    }
}
